package com.songkun.template.ui.base;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.view.KeyEvent;

import com.songkun.template.R;
import com.songkun.template.databinding.ActivityBaseBinding;
import com.songkun.template.databinding.ActivityBaseWebviewBinding;
import com.songkun.template.utils.ILog;
import com.songkun.template.viewmodel.BaseWebViewViewModel;

import java.lang.reflect.Constructor;


/**
 * @描述: 简单的Ｈ5页面展示地址
 * @项目名: ugou
 * @包名: com.ugou88.ugou.ui.my.activity
 * @类名:
 * @作者: soongkun
 * @创建时间: 2016/4/29 13:16
 */

public class BaseWebViewActivity extends CommonActivity {


    private ActivityBaseWebviewBinding mBinding;
    private BaseWebViewViewModel mViewModel;

    private String mTitle = "百度一下.你就知道";
    private String mPageurl = "http://www.baidu.com";
    private String mJsClassName;
    private String mJsFuncName;


    @Override
    protected void initHeader() {
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            mTitle = bundle.getString("title");
            mPageurl = bundle.getString("pageurl", "http://www.ugou88.com");

            /**
             * js的类全称
             */
            mJsClassName = bundle.getString("JsClassName");
            mJsFuncName = bundle.getString("JsFuncName");
        }

        getActivityBaseViewBinding().toolbar.setTitle(mTitle);
    }


    @Override
    protected void initContentView() {
        mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_base_webview,null,false);
        setContentView(mBinding.getRoot());

        mViewModel = new BaseWebViewViewModel(mBasebinding);

        mViewModel.setTitle(mTitle);
    }


    @Override
    public void initData() {
        //初始化浏览器配置
        mViewModel.initWebView(mBinding.homeWv);

        initJSSuppport();
        mViewModel.loadUrl(mPageurl);
    }


    /**
     * 初始化js配置
     */
    private void initJSSuppport() {

        if(mJsClassName == null && mJsFuncName == null){
            return;
        }

        //在js中调用本地java方法
        try {
            Class<?> clazz = Class.forName(mJsClassName);
            Constructor<?> constructor = clazz.getConstructor(Context.class);
            Object o = constructor.newInstance(this);

            mBinding.homeWv.addJavascriptInterface(o, mJsFuncName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mBinding.homeWv.canGoBack()) {
            mBinding.homeWv.goBack();// 返回前一个页面
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


}
